package com.xss.ipctest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.xss.ipctest.model.User;
import com.xss.ipctest.utils.Constant;
import com.xss.ipctest.utils.MyUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class SecondActivity extends AppCompatActivity{
    private static final String TAG = "SecondActivity";
    private TextView textView;
    private TextView textView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        textView = findViewById(R.id.text1_second);
        textView2 = findViewById(R.id.text2_second);
//        User user=getIntent().getParcelableExtra("user_data");
//        textView.setText(user.getUserName()+user.isMale+ Constant.flag);
        Bundle bundle = getIntent().getExtras();
        if (null == bundle) {
            Toast.makeText(this, "bundle id null", Toast.LENGTH_SHORT).show();
        } else {
            User user = bundle.getParcelable("user_data");
            String other_data = bundle.getString("other_data");
            textView.setText("静态常量：" + Constant.flag + "\n"
                    + "其他信息：" + other_data + "\n"
                    + "自定义对象：" + user.getUserName());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        recoverFromFile();
    }

    private void recoverFromFile() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                User user = null;
                File cacheFile = new File(Constant.CACHE_FILE_PATH);
                if (cacheFile.exists()) {
                    ObjectInputStream objectInputStream = null;
                    try {
                        objectInputStream = new ObjectInputStream(new FileInputStream(cacheFile));
                        user = (User) objectInputStream.readObject();
                        //查看log时注意选择的进程
                        Log.i(TAG, "run:===================== " + user.getUserName());
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        MyUtils.close(objectInputStream);
                    }
                }
            }
        }).start();
    }
}
